<template>
  <el-card>
    <!-- 表单 -->
    <el-form inline>
      <el-form-item>
        <el-input v-model="searchRoleName" placeholder="角色名称" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getRolesPageList()" @keyup.enter="getRolesPageList()">查询</el-button>
        <el-button @click="resetRoleList()">清空</el-button>
      </el-form-item>
    </el-form>
    <!-- 功能按钮 -->
    <div class="addAndDelete">
      <el-button type="primary" @click="saveRole()">添加</el-button>
      <el-button type="danger">批量删除</el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="roleList" v-loading="loading" stripe border style="width: 100%">
      <el-table-column type="selection" align="center" width="50" />
      <el-table-column label="序号" align="center" type="index" width="80" />
      <el-table-column label="角色名称">
        <template v-slot="{row, $index}">
          <span v-if="!row.edit">{{row.roleName}}</span>
          <span v-else>
            <el-input 
              :ref="input => inputListRef[$index] = input" 
              v-model="row.roleName" 
              size="small" 
              style="width: 60%; margin-right: 10px"
              
            ></el-input>
            <el-button type="warning" :icon="CircleClose" size="small" @click="readOnlyModel(row)">取消</el-button>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template v-slot="{row, $index}">
          <el-button type="info" title="分配权限" :icon="InfoFilled" size="small" @click="toRoleAuth(row)"></el-button>
          <el-button v-if="row.edit" type="success" title="更新" :icon="Check" size="small" @click="updateRoleInfo(row)"></el-button>
          <el-button v-else type="primary" title="编辑" :icon="Edit" size="small" @click="editRoleName(row, $index)"></el-button>
          <el-button type="danger" title="删除" :icon="Delete" size="small" @click="deleteRoleInfo(row)"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:currentPage="pageNo"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 20, 40]"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="getRolesPageList(1, val)"
      @current-change="getRolesPageList(val, pageSize)"
      style="margin-top: 20px"
    />
  </el-card>
</template>
<script lang="ts">
export default {
  name: 'Role'
}
</script>
<script lang="ts" setup>

import {ref, reactive, onMounted, nextTick} from 'vue'
// 引入消息提示组件
import {ElMessage, ElMessageBox} from 'element-plus'
// 引入图标组件
import { Search, Delete, Edit, InfoFilled, Check, CircleClose } from '@element-plus/icons-vue'

// 引入角色相关的接口函数
import {getRolesPageListApi, saveOrUpdateApi, removeRoleByIdApi, batchRemoveRolesApi} from '@/api/acl/role'
// 引入角色相关的接口类型
import type {RoleListModel, RoleModel} from '@/api/acl/model/roleModel'

// 引入Api
import {useRouter} from 'vue-router'
// 定义router
const router = useRouter()

const loading = ref(false) // 定义载入效果的标识
const total = ref(0) // 定义数据总数
const pageNo = ref(1) // 定义当前页码
const pageSize = ref(5) // 定义每页展示的数据个数

const roleList = ref<RoleListModel>([]) // 定义存储角色列表数据
const roleInfo = ref<RoleModel>() // 定义存储角色信息对象
const searchRoleName = ref<string>('') // 定义搜索关键字
const inputRoleName = ref<string>('') // 定义输入框内角色名称
const inputListRef = ref<HTMLInputElement[]>([]) // 定义存储输入框实例对象的数组


// 获取角色分页列表
const getRolesPageList = async (page: number = pageNo.value, limit: number = pageSize.value) => {
  loading.value = true
  // 更新页码 每页展示数量
  pageNo.value = page
  pageSize.value = limit
  const res = await getRolesPageListApi(page, limit, {
    roleName: searchRoleName.value
  })
  loading.value = false
  roleList.value = res.items
  total.value = res.total
}
// 添加角色
const saveRole = async () => {
  ElMessageBox.prompt('请输入新名称', '添加角色', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValidator(val) {
      return !val ? false: true
    },
    inputErrorMessage: '角色名不能为空',
  })
    .then(async ({ value }) => {
      const flag = roleList.value.findIndex(item => item.roleName === value.trim()) !== -1 
      if (flag) {
        ElMessage.warning('角色名称已存在')
        return
      }
      // 更新角色信息对象
      roleInfo.value = {
        id: undefined,
        roleName: value.trim()
      }
      // 调用新增接口函数
      await saveOrUpdateApi(roleInfo.value)
      // 更新列表数据 重新渲染
      getRolesPageList()
      ElMessage({
        type: 'success',
        message: '添加成功',
      })
    })
    .catch(() => {
      ElMessage({
        type: 'warning',
        message: '取消添加',
      })
    })
}
// 移除角色对象
const deleteRoleInfo = async (row: RoleModel) => {
  ElMessageBox.confirm(
    `确定删除名为${row.roleName}的角色吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async () => {
      await removeRoleByIdApi(row.id as string)
      // 更新列表数据 重新渲染
      getRolesPageList()
      ElMessage({
        type: 'success',
        message: '删除成功',
      })

    })
    .catch(() => {
      ElMessage({
        type: 'warning',
        message: '取消删除',
      })
    })
}
// 进入角色名称编辑模式
const editRoleName = (row: RoleModel, index: number) => {
  // 进入编辑模式
  row.edit = true
  // 
  inputRoleName.value = row.roleName // 存储原始角色名
  // 获取输入框光标
  nextTick(() => {
    inputListRef.value[index].focus()
  }) 
}
// 进入角色名只读模式
const readOnlyModel = (row: RoleModel) => {
  // 进入编辑模式
  row.edit = false
  row.roleName = inputRoleName.value
}
// 更新角色名称
const updateRoleInfo = async (row: RoleModel) => {
  // 判断输入值是否变化 没变化就不发送请求
  if (row.roleName === inputRoleName.value) return row.edit = false
  try {
    await saveOrUpdateApi(row)
    ElMessage.success('更新角色成功')
    row.edit = false
  } catch (error: any) {
    ElMessage.warning(error.message)
  }
} 
// 清空
const resetRoleList = () => {
  searchRoleName.value = ''
  getRolesPageList()
}
// 分配权限按钮回调
const toRoleAuth = (row: RoleModel) => {
  router.push({
    // 命名路由
    name: 'RoleAuth',
    params: {
      role_name: row.roleName,
      id: row.id
    }
  })
}


// 页面挂载完毕
onMounted(() => {
  getRolesPageList()
}) 
</script>
<style scoped>
.addAndDelete {
  margin: 20px 0;
}
:deep(.el-overlay.is-message-box .el-overlay-message-box) {
  top: -100px;
}
</style>